<?php
/**
 * Set layout and mime type if the request has the portable device parameter set.
 * 
 * params:
 *  - String layout
 *  
 * Example filters.yml integration:
 * 
 * <pre>
jfPortableDeviceFilter:
  class:  jfPortableDeviceFilter
  param:
    layout: layout_device_portable_ajax
    defaultFormFormatterName: jfPD
</pre>
 *
 */
class jfPortableDeviceFilter extends sfFilter
{

	protected static $_layout = null;
	
	/**
	 * You can override the default layout parameter defined in filters.yml
	 * 
	 * Setter for {@property self::$_layout}
	 * 
	 * @param String | bool $value
	 */
	public static function setLayout($value) {
		self::$_layout = $value;
	}
	
  public function execute($filterChain)
  {
    $context  = $this->getContext();
    $request  = $context->getRequest();

    if ($request->getParameter('jfPD_device') === 'portable') {
      jfPortableDevice::setIsPortableDevice(true);
    	$layout = isset(self::$_layout) ? self::$_layout : $this->getParameter('layout');
     	$context->getActionStack()->getFirstEntry()->getActionInstance()->setLayout($layout);
    	if(class_exists('sfWidgetFormSchema')) { // compatibility with symfony 1.0
    		sfWidgetFormSchema::setDefaultFormFormatterName($this->getParameter('defaultFormFormatterName', 'jfPD'));
    	}
    	
    	jfPortableDevice::setPageAttribute('data-url', htmlspecialchars($request->getUri()));
      jfPortableDevice::setPageAttribute('data-clean-url', htmlspecialchars(jfPortableDevice::cleanUrl($request->getUri())));
    }
    
    $filterChain->execute();

		if (jfPortableDevice::isPortableDevice()) {
			
			if (jfPortableDevice::getConfig('lazyLoadImages') && $request->isXmlHttpRequest()) {
				$response  = $context->getResponse();
		    $content = $response->getContent();
		    $content = preg_replace('/(<img.*)(src=)([\'|\"].*>)/', '$1data-jfPD-src=$3', $content);
		    $response->setContent($content);
			}

			if (jfPortableDevice::isNativeApp()) {
			  sfConfig::set('sf_web_debug', false);
			}
			
		}
		
  }
}
